package edu.cibertec.action;

import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class MantenimientoUsuariosAction extends Action {
	SqlMapClient sqlMap;
	
	public ActionForward execute ( ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
		
    	try {
    		String resource = "SqlMapConfigApplication.xml";
    		Reader reader = Resources.getResourceAsReader (resource);
    		sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
    	} catch (Exception e) {
    		e.printStackTrace();
    		throw new RuntimeException ("Error cargando configuracion en RedireccionandoAction Cause: " + e);
    	}
    	
		String forwardName = "failure";
		String parametro = request.getParameter("param1");
		String modo = request.getParameter("modo");
		int i = 0;
		
		if ( modo.equals("DELETE")) {
			i = sqlMap.delete("eliminaUsuario", parametro);
		} else {
			i = sqlMap.update("actualizaUsuario", parametro);
		}

		if ( i > 0 ) {
			forwardName = listaUsuarios(request);
		}
		
		return mapping.findForward(forwardName);
	}
        
	private String listaUsuarios(HttpServletRequest request) throws SQLException {
		
   	    List listaUsuarios = sqlMap.queryForList("getAllUsuarios");
    	
    	if ( listaUsuarios.size() > 0 ) {
    		System.out.println("**PasoPorStringlistaUsuarios**");
            HttpSession session = request.getSession();
            session.setAttribute("listaUsuario",listaUsuarios);
        	return "f2";
        } else {
        	return "failure";
        }
	}
	
}
